
const net = require("net")
const path = require('path')
const fs = require("fs")

module.exports = class TcpClient {

  send(ip, filePath) {

    let fileInfo = fs.statSync(filePath)

    let socket = net.createConnection(9186, ip, ()=> {

      let buffer = Buffer.allocUnsafe(0)
      var str = '阿林';
      var nameBuffer = Buffer.from(str)
      buffer = Buffer.concat([buffer, nameBuffer]);
    
      let fileName = path.basename(filePath);
      let fileNameBuffer = Buffer.from(fileName)
    
    
      var nameLengthBuff = Buffer.allocUnsafe(4) //文件名长度
      nameLengthBuff.writeUInt32BE(fileNameBuffer.length)
      buffer = Buffer.concat([buffer, nameLengthBuff]);
    
      var dataLengthBuff = Buffer.allocUnsafe(4) //数据长度
      dataLengthBuff.writeUInt32BE(fileInfo.size)
      buffer = Buffer.concat([buffer, dataLengthBuff]);
    
      buffer = Buffer.concat([buffer, fileNameBuffer]); //写入文件名
    
    
      socket.write(buffer); //向服务端发送

      let readerStream = fs.createReadStream(filePath);
      readerStream.pipe(socket);
    
      socket.on('data',function(data){
        console.log(data); //接受服务端数据
      });
    });
  }
}

